const express = require('express');
const router = express.Router();
const cryto = require('crypto')
const oicq = require("oicq");
const schedule = require('node-schedule');
const { zaoCi } = require('./qqConfig/thesaurus')
const qunlistConfig = require('./qqConfig/qunlist')
const defaultConfig = require('./qqConfig/config')
const path = require('path');
const orderList = require('./qqConfig/order')

// qq配置
const { getAncestor, getListImg, getRandomInt, } = require('./qqConfig/fn')
// 配置初始up
global.upName = 'sj'
// 图片配置
const xianList = defaultConfig.xianList
// 群配置
const qunList = qunlistConfig
// 托管的QQ号配置 
const { uin, pwd } =
  defaultConfig.account
// defaultConfig.accountTest // 把前面的//去除即可使用测试号
// 复刻消息 
let fukeTime = ''
let fukeImg = ''

const password_md5 = cryto.createHash('md5').update(pwd).digest('hex')
const config = defaultConfig.qqConfig
const client = oicq.createClient(uin, config);

// 登录
client.login(password_md5);
client.on("system.login.captcha", () => {
  process.stdin.once("data", input => {
    client.captchaLogin(input);
  });
});
// 上线后
client.on("system.online", () => {
  // 上线每小时执行一次
  setTimeout(() => {
    // 获取群
    getQunList()
  }, 1000 * 60 * 60)
});
// 获取群
async function getQunList() {
  let qunlists = client.getGroupList().data
  setTimeout(() => {
    qunlists.forEach(item => {
      if (Object.keys(qunlistConfig).indexOf(item.group_id) != -1) {
        qunList[item.group_id] = { name: item.group_name }
      } else {
        qunList[item.group_id] = { ...qunlistConfig[item.group_id], name: item.group_name }
      }
    })
  }, 10000);
}

// 监听信息
client.on("message", data => {
  // 私聊小助手时
  if (data.message_type == "private") {
    privateMsg(data)
    return
  }
  // 信息处理
  defaultMessage(data)
  // @小助手时处理
  if (data.raw_message.indexOf('[CQ:at,qq=' + uin) != -1) {
    setTimeout(() => {
      messageProcess(data, data.message[1].data.text)
    }, 0)
  }
  if (qunList[data.group_id].ka) {
    messagePraise(data)
  }
});

// 监听群动态
client.on("notice", data => {
  // 处理加群
  if (data.sub_type == 'increase' && qunList[data.group_id]) {
    if (qunList[data.group_id].hello) {
      client.getStrangerInfo(data.user_id).then(res => {
        let sex = res.data.sex == "male" ? "littleboy" : 'littlegirl'
        client.sendGroupMsg(data.group_id, `[CQ:at,qq=${data.user_id},text=@${data.nickname}]\n[CQ:image,file=file:///${path.resolve(__dirname, `../public/images/${sex}.jpg`)}]
        欢迎新的光之子！`)
      })
    }
  }
});

// 处理对话
function defaultMessage(data) {
  let text = data.message[0].data.text ? data.message[0].data.text : ''
  let sex = data.sender.sex == '小可爱'
  let sj = getRandomInt(2)
  let arr = orderList({ sex, sj, fukeTime, fukeImg })
  let next = false
  // 正常聊天指令
  for (let v of arr) {
    if (next) return
    v.key.forEach(tev => {
      if (next) return
      if (text.indexOf(tev) != -1) {
        next = true
        setTimeout(() => {
          client.sendPrivateMsg(data.user_id, v.val)
        }, 0)
      }
    })
  }
}

// 私聊
function privateMsg(data) {
  let text = data.message[0].data.text ? data.message[0].data.text : ''
  // 私聊
  // 处理先祖位置
  if (xianList.indexOf(text) != -1) {
    setTimeout(() => {
      client.sendPrivateMsg(data.user_id, `${xianList[xianList.indexOf(text)]}位置来咯！\n [CQ:image,cache=0,file=file:///${path.resolve(__dirname, `../public/images/${xianList[xianList.indexOf(text)]}.jpg`)}]`)
    }, 0)
  } else if (text.indexOf("菜单") != -1) {
    setTimeout(() => {
      client.sendPrivateMsg(data.user_id, defaultConfig.menu)
    }, 0)
  }
  else {
    defaultMessage(data)
  }
}

// @时处理函数
function messageProcess(data, text) {
  if (text.indexOf(" 菜单") != -1) {
    client.sendGroupMsg(data.group_id, defaultConfig.menu)
    return
  }
}

// 群发
async function qunPush() {
  for (let item of Object.keys(qunList)) {
    if (item == "767164437") {
      sendMsg(item, 'sj')
      console.log('发送每日任务')
    }
  }
}

// 消息配置
let msgObj = {
  sj(item, t) {
    client.sendGroupMsg(item, `[CQ:image,cache=0,file=file:///${path.resolve(__dirname, `../public/images/${t}list.jpg`)}]` + '\n ' + zaoCi[getRandomInt(zaoCi.length)])
  },
  fk(item) {
    client.sendGroupMsg(item, `近期复刻先祖消息！${fukeTime}\n [CQ:image,cache=0,file=${fukeImg}]`)
  }
}
// 发送定时消息
function sendMsg(item, type) {
  let sj = getRandomInt(2)
  setTimeout(() => {
    msgObj[type](item, sj)
  }, 10)
}

// 定时函数
function scheduleCronstyle() {
  schedule.scheduleJob('00 10 2 * * *', () => {
    // 获取每日任务
    getListImg()
    // 获取复刻
    getAncestor({ id: "12416722" }).then(res => {
      fukeTime = res.fukeTime
      fukeImg = res.fukeImg
    })
  })
  //每天时:
  schedule.scheduleJob('59 59 23 * * *', async () => {
    let time = new Date().getHours()
    if (time % 3 == 0) {
      // 更新群列表
      getQunList()
    }
  });
}
// 获取每日
getListImg()
// 定时处理
scheduleCronstyle()
// 获取复刻
getAncestor({ id: "12416722" }).then(res => {
  fukeTime = res.fukeTime
  fukeImg = res.fukeImg
})

/* GET home page. 群发信息 */
router.get('/', function (req, res, next) {
  res.send('qq');
});

module.exports = router;